package fr.umlv.jee.jawp.service.subscribe;

import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import fr.umlv.jee.jawp.persistence.object.Order;
import fr.umlv.jee.jawp.persistence.object.Product;
import fr.umlv.jee.jawp.service.aws.Aws;

public class MailEngine {
  public void sendOrderMail(Order order, List<Product> list) {
    String[] dest = { order.getCustomer(), "claudien.barbier@gmail.com",
        "lorie.vaillant@gmail.com", "razafimanohy@googlemail.com",
        "herve.bassinot@gmail.com" };
    String subject = "JAWP : Validation of your order";

    StringBuilder msg = new StringBuilder();
    msg.append("<h2>Dear " + order.getCustomer() + "</h2>");
    msg.append("Thank you for your recent purchase on JAWP.<br />");
    msg.append("Your order is : " + order.getStatus() + "<br /><br />");

    Aws aws = new Aws();
    for (Product p : list) {
      Map<String, String> map = aws.findArticleByItemID(p.getASIN()).get(0);
      msg.append("<img src='" + map.get("LargeImage.URL")
          + "' title='image' width='80px' />" + map.get("Title") + "<br />");
    }
    msg.append("<br />Thk. All team of JAWP.");
    postMails(dest, subject, msg.toString());
  }

  public void postMails(String dest[], String subject, String msg) {
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props
        .put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(props,
        new javax.mail.Authenticator() {
          protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("jawp.umlv@gmail.com",
                "jawp.umlv");
          }
        });

    // DEBUG
    session.setDebug(false);
    try {

      InternetAddress[] addressTo = new InternetAddress[dest.length];
      for (int i = 0; i < dest.length; i++) {
        addressTo[i] = new InternetAddress(dest[i]);
      }

      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress("no-reply@jawp.com"));
      message.setRecipients(Message.RecipientType.TO, addressTo);
      message.setSubject(subject);
      // message.setText(msg);
      message.setContent(msg, "text/html; charset=ISO-8859-15");
      Transport.send(message);

    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }

  }
}
